package at.pp.match3.sprite;

import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;

import at.pp.match3.activity.Color;
import at.pp.match3.activity.listener.ISpriteSelectionListener;

public class GameButton extends SelectableSprite {

    public int gridPositionX;
    public int gridPositionY;
    public boolean isSelected;
    public Color color;

    public GameButton(float pX, float pY, int gridPositionX, int gridPositionY,
            TiledTextureRegion pTextureRegion,
            ISpriteSelectionListener spriteSelectionLsitener) {
        super(pX, pY, pTextureRegion, spriteSelectionLsitener);
        this.gridPositionX = gridPositionX;
        this.gridPositionY = gridPositionY;
    }

    public GameButton(float pX, float pY, TiledTextureRegion pTextureRegion,
            ISpriteSelectionListener spriteSelectionLsitener) {
        super(pX, pY, pTextureRegion, spriteSelectionLsitener);
    }

    @Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
            float pTouchAreaLocalX, float pTouchAreaLocalY) {
        if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
            spriteSelectionListener.onSpriteSelected(this);
        }
        return true;
    }

    public boolean isExchangable(GameButton otherButton) {
        int differenceX = computeDifference(this.gridPositionX,
                otherButton.gridPositionX);
        int differenceY = computeDifference(this.gridPositionY,
                otherButton.gridPositionY);
        return (differenceX == 1 && differenceY == 0)
                || (differenceX == 0 && differenceY == 1);
    }

    private int computeDifference(int gridPosition, int otherGridPosition) {
        return gridPosition < otherGridPosition ? otherGridPosition
                - gridPosition : gridPosition - otherGridPosition;
    }

    public void setColor(Color color) {
        this.color = color;
        setUnselectedTile();
    }
    
    public void setColor(int color) {
        this.color = Color.values()[color];
        setUnselectedTile();
    }
    
    public void setUnselectedTile() {
        this.setCurrentTileIndex(this.color.ordinal() * 2);
    }
    
    public void setSelectedTile() {
        this.setCurrentTileIndex((this.color.ordinal() * 2) + 1);
    }
    
    @Override
    public boolean equals(Object o) {
        GameButton button = (GameButton) o;

        return (this.gridPositionX == button.gridPositionX)
                && (this.gridPositionY == button.gridPositionY);
    }

}
